//
//  RoundedRectButton.m
//  SecretAlbums
//
//  Created by BabyFinancial on 15/6/18.
//  Copyright (c) 2015年 BabyFinancial. All rights reserved.
//

#import "RoundedRectButton.h"

#define LineWidth 1.0f
#define TitleFontSize 20.0f

@interface RoundedRectButton ()

@property (nonatomic, strong) CAShapeLayer *shapeLayer;

@end

@implementation RoundedRectButton

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 添加边框
        self.shapeLayer = [CAShapeLayer layer];
        self.shapeLayer.lineWidth = LineWidth;
        self.shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        [self.layer addSublayer:self.shapeLayer];
        
        // 添加文本
        self.titleLabel = [UILabel new];
        self.titleLabel.textColor = [UIColor whiteColor];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont systemFontOfSize:TitleFontSize];
        [self addSubview:self.titleLabel];
    }
    
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    // 边框
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:self.bounds.size.height/2];
    self.shapeLayer.path = path.CGPath;
    self.shapeLayer.strokeColor = self.tintColor.CGColor;
    
    // 文本
    self.titleLabel.bounds = self.bounds;
    self.titleLabel.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
}

#pragma mark - 点击方法

- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    [super beginTrackingWithTouch:touch withEvent:event];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(touchRoundedRectButton:)]) {
        [self.delegate touchRoundedRectButton:self];
    }
    
    [CATransaction begin];
    [CATransaction setAnimationDuration:0.1f];
    
    self.shapeLayer.fillColor = self.tintColor.CGColor;
    
    [CATransaction commit];
    
    return YES;
}

- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    [super endTrackingWithTouch:touch withEvent:event];
    
    [CATransaction begin];
    [CATransaction setAnimationDuration:1.0f];
    
    self.shapeLayer.fillColor = [[UIColor clearColor] CGColor];
    
    [CATransaction commit];
}

- (void)cancelTrackingWithEvent:(UIEvent *)event
{
    [super cancelTrackingWithEvent:event];
    
    [CATransaction begin];
    [CATransaction setAnimationDuration:1.0f];
    
    self.shapeLayer.fillColor = [[UIColor clearColor] CGColor];
    
    [CATransaction commit];
}

@end
